﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    internal class 打印文档
    {

        /// <summary>
        /// 每个月1号整理文件，写入日期早于比较日期的文件放于新目录
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="mode">0-每个月整理，1-每年整理</param>
        public static void SortFilesByDate(string folder, int mode)
        {
            try
            {
                //仅月初检查
                if (!SortFiles || 5 < DateTime.Now.Day || !Directory.Exists(folder))
                {
                    return;
                }
                DateTime CompareDate = DateTime.Now;
                switch (mode)
                {
                    case 0:
                    default:
                        CompareDate = CompareDate.AddMonths(-1);    //假如今天为2024-02-07，变为2024-01-07
                        CompareDate = new DateTime(CompareDate.Year, CompareDate.Month, 1);//变为2024-01-01
                        break;

                    case 1:
                        CompareDate = CompareDate.AddYears(-1);    //假如今天为2024-02-07，变为2023-02-07
                        CompareDate = new DateTime(CompareDate.Year, 1, 1);//变为2023-01-01
                        break;
                }
                if (!folder.EndsWith("\\"))
                {
                    folder += "\\";
                }
                //以上个月日期命名文件夹，如"2024-01"
                string monthFolder = $"{folder}{CompareDate.ToDateString().Substring(0, 7)}\\";

                //移动文件，将早于比较日期的文件放于新目录
                string[] files = Directory.GetFiles(folder);
                foreach (var file in files)
                {
                    FileInfo info = new FileInfo(file);
                    //早于比较日期
                    if (0 > info.LastWriteTime.CompareTo(CompareDate))
                    {
                        Directory.CreateDirectory(monthFolder);
                        info.MoveTo(monthFolder + info.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteException(ex);
            }
        }

        /// <summary>
        /// 校验产品流程状态接口
        /// </summary>
        /// <param name="sN"></param>
        /// <returns></returns>
        public ParameterOut CheckSNPost(string sN)
        {
            string logData = "";
            try
            {
                CheckSN checkSN = new CheckSN()
                {
                    SN = sN,
                    LWPID = DATAS.LWPID_HJ


                };
                string jsonData = JsonData.Serial(checkSN);
                string result = WebService.GetContentPost(DATAS.URL_CheckProductProcess_HJ, "application/json", jsonData, Encoding.UTF8, 3000);
                logData = jsonData + "-||||-" + result;
                return (JsonData.Deserial<ParameterOut>(result));
            }
            catch (Exception ex)
            {
                logData = "EX-CheckSNPost" + ex.StackTrace + ex.Message.ToString();
                return new ParameterOut();
            }
            finally
            {
                lock (lockCheckSNPost)
                {
                    string folder = Application.StartupPath + "\\Log\\MESLog\\";
                    Directory.CreateDirectory(folder);
                    Log.SortFilesByDate(folder, 0);

                    string path = $"{folder}{DateTime.Now.ToDateString()}.log";
                    File.AppendAllText(path, "进站" + DateTime.Now.ToString() + logData.ToString() + "\r\n");
                }
            }
        }

        public class JsonData
        {
            public static string Serial(object value)
            {
                return JsonConvert.SerializeObject(value);
            }

            public static object Deserial(string value)
            {
                return JsonConvert.DeserializeObject(value);
            }

            public static Dictionary<object, object> DeserialDict(string value)
            {
                return JsonConvert.DeserializeObject<Dictionary<object, object>>(value);
            }

            public static T Deserial<T>(string value)
            {
                return JsonConvert.DeserializeObject<T>(value);
            }

            public static string CreateJStrForData(string Result, string Msg, string Data)
            {
                return Serial(new
                {
                    Result,
                    Msg,
                    Data
                });
            }
        }

        public static string GetContentPost(string uri, string contentType, string data, Encoding coding, int timeout = 10000)
        {
            coding = coding ?? Encoding.UTF8;
            byte[] buffer = !string.IsNullOrEmpty(data) ? coding.GetBytes(data) : new byte[0];

            WebRequest request = WebRequest.Create(uri);
            request.Method = "POST";
            request.ContentType = contentType;
            request.ContentLength = buffer.Length;
            request.Proxy = null;
            //request.Headers.Add("Authorization", Authorization);  //添加Authorization头
            request.Timeout = timeout;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(buffer, 0, buffer.Length);
            }

            try
            {
                using (WebResponse response = request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    return new StreamReader(stream, coding).ReadToEnd();
                }
            }
            catch (WebException ex) when (ex.Response != null)
            {
                using (var response = ex.Response)
                using (var stream = response.GetResponseStream())
                {
                    string errorContent = new StreamReader(stream, coding).ReadToEnd();

                    //获取HTTP状态码
                    HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode;

                    //写入EX的massage 
                    throw new WebException($"请求失败: {ex.Status}" +
                        $"\r\n HTTP状态码:{statusCode} " +
                        $"\r\n URL:{uri} ", ex);
                }
            }
        }

    }
}
